from typing import List, Optional, Dict, Any
from datetime import datetime
from models.models import ChatSessions, DetailedConversations
from peewee import fn
import uuid



class SessionService:
    """会话管理服务 - 处理历史对话记录和会话管理"""
    
    def get_all_sessions(self, page: int = 1, size: int = 20) -> Dict[str, Any]:
        """
        获取所有会话列表
        
        Args:
            user_id: 用户ID（如果有多用户系统）
            page: 页码
            size: 每页大小
            
        Returns:
            包含会话列表和分页信息的字典
        """
        query = ChatSessions.select().where(ChatSessions.is_deleted == False)

        # 按更新时间倒序排列
        query = query.order_by(ChatSessions.updated_at.desc())

        # 分页
        total = query.count()
        sessions = query.paginate(page, size)
        
        return {
            "sessions": [self._format_session(session) for session in sessions],
            "pagination": {
                "page": page,
                "size": size,
                "total": total,
                "pages": (total + size - 1) // size
            }
        }
    
    def get_session_by_id(self, session_id: str) -> Optional[Dict[str, Any]]:
        """
        根据会话ID获取会话详情
        
        Args:
            session_id: 会话ID
            
        Returns:
            会话详情字典，如果不存在返回None
        """
        try:
            session = ChatSessions.get(
                ChatSessions.session_id == session_id,
                ChatSessions.is_deleted == False
            )
            return self._format_session(session)
        except ChatSessions.DoesNotExist:
            return "该对话不存在/已删除"
    
    def get_conversation_history(self, session_id: str, page: int = 1, size: int = 50) -> Dict[str, Any]:
        """
        获取指定会话的对话历史
        
        Args:
            session_id: 会话ID
            page: 页码
            size: 每页大小
            
        Returns:
            包含对话历史和分页信息的字典
        """
        query = DetailedConversations.select().where(
            DetailedConversations.session_id == session_id,
            DetailedConversations.is_deleted == False
        ).order_by(DetailedConversations.created_at.asc())

        total = query.count()
        conversations = query.paginate(page, size)
        
        return {
            "conversations": [self._format_conversation(conv) for conv in conversations],
            "pagination": {
                "page": page,
                "size": size,
                "total": total,
                "pages": (total + size - 1) // size
            }
        }
    
    def create_new_session(self) -> Dict[str, Any]:
        """
        创建新会话
        
        Args:
            title: 会话标题
            
        Returns:
            新创建的会话信息
        """

        
        session_id = str(uuid.uuid4())
        session = ChatSessions.create(
            session_id=session_id,
            title=f"新对话 {datetime.now().strftime('%Y-%m-%d %H:%M')}"
        )
        
        return self._format_session(session)

    def create_new_title(self, session_id: str):
        # TODO  后面需要在会话结束，（默认创建新会话为 会话结束），根据历史聊天记录，生成新title
        return




    def delete_session(self, session_id: str) -> bool:
        """
        删除会话（软删除）
        
        Args:
            session_id: 会话ID
            
        Returns:
            是否删除成功
        """
        try:
            session = ChatSessions.get(
                ChatSessions.session_id == session_id,
                ChatSessions.is_deleted == False
            )
            session.is_deleted = True
            session.deleted_at = datetime.now()
            session.save()
            return True
        except ChatSessions.DoesNotExist:
            return "删除失败"
    
    def update_session_title(self, session_id: str, title: str) -> bool:
        """
        更新会话标题
        
        Args:
            session_id: 会话ID
            title: 新标题
            
        Returns:
            是否更新成功
        """
        try:
            session = ChatSessions.get(
                ChatSessions.session_id == session_id,
                ChatSessions.is_deleted == False
            )
            session.title = title
            session.updated_at = datetime.now()
            session.save()
            return True
        except ChatSessions.DoesNotExist:
            return "title更新失败"
    
    def search_conversations(self, keyword: str, page: int = 1, size: int = 20) -> Dict[str, Any]:
        """
        搜索对话内容
        
        Args:
            keyword: 搜索关键词
            session_id: 限制在特定会话内搜索（可选）
            page: 页码
            size: 每页大小
            
        Returns:
            包含搜索结果和分页信息的字典
        """
        query = DetailedConversations.select().where(
            DetailedConversations.is_deleted == False,
            (DetailedConversations.user_input.contains(keyword)) |
            (DetailedConversations.final_response.contains(keyword))
        ).order_by(DetailedConversations.created_at.desc())

        
        total = query.count()
        conversations = query.paginate(page, size)
        
        return {
            "conversations": [self._format_conversation(conv) for conv in conversations],
            "pagination": {
                "page": page,
                "size": size,
                "total": total,
                "pages": (total + size - 1) // size
            }
        }
    
    def get_session_statistics(self, session_id: str) -> Dict[str, Any]:
        """
        获取会话统计信息
        
        Args:
            session_id: 会话ID
            
        Returns:
            会话统计信息
        """
        try:
            session = ChatSessions.get(
                ChatSessions.session_id == session_id,
                ChatSessions.is_deleted == False
            )
            
            # 统计对话数量
            conversation_count = DetailedConversations.select().where(
                DetailedConversations.session_id == session_id,
                DetailedConversations.is_deleted == False
            ).count()
            
            # 统计平均处理时间
            avg_processing_time = DetailedConversations.select(
                fn.AVG(DetailedConversations.processing_time)
            ).where(
                DetailedConversations.session_id == session_id,
                DetailedConversations.is_deleted == False,
                DetailedConversations.processing_time.is_null(False)
            ).scalar()
            
            return {
                "session_id": session_id,
                "title": session.title,
                "created_at": session.created_at,
                "updated_at": session.updated_at,
                "conversation_count": conversation_count,
                "avg_processing_time": avg_processing_time or 0
            }
        except ChatSessions.DoesNotExist:
            return None
    
    def _format_session(self, session: ChatSessions) -> Dict[str, Any]:
        """格式化会话对象"""
        return {
            "session_id": session.session_id,
            "title": session.title,
            "created_at": session.created_at,
            "updated_at": session.updated_at,
            "message_count": session.message_count
        }
    
    def _format_conversation(self, conversation: DetailedConversations) -> Dict[str, Any]:
        """格式化对话对象"""
        return {
            "conversation_id": conversation.conversation_id,
            "session_id": conversation.session_id,
            "user_input": conversation.user_input,
            "final_response": conversation.final_response,
            "model_name": conversation.model_name,
            "processing_time": conversation.processing_time,
            "created_at": conversation.created_at
        } 